<template>
	<div class="zh-database-push-check">
		<div class="zh-table"
			v-loading="testLoading.status"
	    	:element-loading-text="testLoading.txt">
			<div class="zh-table-open clear">
				<div class="zh-open-left fl">
                    <div style="display: inline-block" v-if="user_level === 0">
                        <div class="open-width" style="width: 120px">
                            <el-select v-model="listParam.platform_id" filterable placeholder="来源学校/教育局">
                                <el-option
                                    v-for="item in platformList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="open-width">
                            <el-input v-model="listParam.keyword" placeholder="试题名称"></el-input>
                        </div>
                    </div>
					<div style="display: inline-block" v-else>
                        <div class="open-width">
                            <el-select v-model="listParam.study_section_id" filterable placeholder="请选择">
                                <el-option
                                v-for="item in orgLevel2"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="open-width">
                            <el-select v-model="listParam.grade_id" filterable  placeholder="请选择">
                                <el-option
                                v-for="item in orgLevel3"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="open-width">
                            <el-select v-model="listParam.subject_id" filterable placeholder="请选择">
                                <el-option
                                v-for="item in orgSubject"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                                </el-option>
                            </el-select>
                        </div>
					</div>
					<el-button type="primary" @click="getList">搜索</el-button>
                    <el-button type="primary" @click="reset">重置</el-button>                 
				</div>
			</div>
			<div class="zh-select-type">
				<div class="clear">
					<div class="stl fl">题型：</div>
					<div class="str fl">
						<span 
							v-for="item in questionTypeData" 
							:key="item.id"
							v-if="checkShowType(item.id)"
							:class="{active : listParam.type_id === item.id}"
							@click="selected(item.id)"
							>
							{{item.name}}
						</span>
					</div>
				</div>
				<div class="clear">
					<div class="stl fl">难度：</div>
					<div class="str fl">
						<span 
							v-for="item in difficultyData" 
							:key="item.id"
							:class="{active2 : listParam.difficulty_id === item.id}"
							@click="selected2(item.id)"
							>
							{{item.name}}
						</span>
					</div>
				</div>
				<!-- <div class="clear">
					<div class="stl fl">类型：</div>
					<div class="str fl">
						<span 
							v-for="item in sourceData" 
							:key="item.id"
							:class="{active3 : listParam.source_id === item.id}"
							@click="selected3(item.id)"
							>
							{{item.name}}
						</span>
					</div>
				</div> -->
			</div>
			<div class="zh-select-type-content">
				<div class="list-option">
					<div class="list-option-title clear">
						<div class="option-title-left fl">
							<span 
								v-for="item in statusArr" 
								:key="item.value"
								:class="{active4 : listParam.status === item.value}"
								@click="selected4(item.value)"
								>
								{{item.name}}
							</span>
						</div>
						<div class="option-title-right fr">共<span style="color:red"> {{total_number}} </span>题</div>
					</div>
					<!-- 循环 -->
					<template v-for="(item,inx) in listData">
						<div class="list-option-content" :key="inx">
							<div class="list-option-explanation clear">
								<div class="option-explanation-left fl">
									<span>{{++inx}}.{{item.question_data.question_type}}</span>
									<span class="left-color-hui">|</span>
									<span>难度：{{item.question_data.difficulty}}</span>
									<span v-html="getStatusTxt(item.status)" :style="getStatusColor(item.status)"></span>
                                    <span>由 {{item.school_name}} 推送</span>
								</div>
								<div class="option-explanation-right fr">
									<el-popover
									  placement="left-end"
									  width="600"
									  trigger="click"
									>
										<div class="list-option-answer">
											<ul>
												<li v-if="[1, 2, 4].includes(item.type_base_id)">
													<span>答案：</span>
													<span class="answer-first color">{{renderAnswer(item.question_data.answer)}}</span>
												</li>
												<li>
													<span>统计：</span>
													<span class="answer-first">本题共被作答
														<span class="answer-second">{{item.question_data.question_info.answer_count}}</span>
														次，正确率为
														<span class="answer-third">{{item.question_data.question_info.true_probability}}%</span>
													</span>
												</li>
												<li class="clear">
													<span class="fl">解析：</span>
													<span v-if="item.question_data.pattern === 1" class="answer-first fl" v-html="getImg(item.question_data.resolve)"></span>
                                                    <span v-else>
                                                        <img :src="host_addr + item.question_data.resolve_image_path" style="max-width:90%" />
                                                    </span>
												</li>
											</ul>
										</div>
									  	<el-button slot="reference" type="text">查看解析</el-button>
									</el-popover>
									<span v-if="parseInt(item.status) === 1">
										<el-button 
											type="primary" size="mini" 
											style="margin-left: 30px"
											@click="approveQuestion(item)"
										>
											批准
										</el-button>
										<el-button 
											type="danger" size="mini"
											@click="rejectQuestion(item)"
										>
											拒绝
										</el-button>
									</span>
									<template v-if="user_multistage === true">
	                                    <span>
	                                        <!-- <input style="margin-left: 30px" type="checkbox" :id="item.id" :value="item.id" v-model="checkedNames"> -->
	                                        <el-button type="danger" size="mini" @click="delQuestion(item)">删除</el-button>
	                                    </span>
	                                 </template>
								</div>
							</div>
                            <ul class="list-option-list">
                                <li v-if="item.question_data.pattern === 1"  v-html="getImg(item.question_data.content)"></li>
                                <li v-else>
                                    <img :src="host_addr + item.question_data.content_image_path" style="max-width:90%" />
                                </li>
                                <template v-for="item2 in item.question_data.option">
                                    <li v-html="item2.name+'.' + getImg(item2.value)"></li>
                                </template>
                            </ul>
						</div>	
					</template>
				</div>
			</div>
		</div>
		<el-pagination
		    @size-change="handleSizeChange"
		    @current-change="handleCurrentChange"
		    :current-page="listParam.page_index"
		    :page-sizes="[10, 20, 30, 40, 50, 100]"
		    :page-size="listParam.page_size"
		    layout="total, sizes, prev, pager, next, jumper"
			v-show="total_number > 10"
		    :total="total_number">
		</el-pagination>
	</div>
</template>
<script>
    import pushLowWin from '@/components/common/push-low-win';

  	export default {
        components: {
			pushLowWin
		},
	    data() {
		    return {
                activePanel: 'platform-check',
                host_addr: sessionStorage.getItem("host_addr"),
                checkedNames: [], /* 保持删除的id */
                checkedPushNames: [], /* 保持推上级/推下级的id */
                platform: '', /* 可推送上级 */
                pid: '', /* 可推送上级id */
                pushUpList: [],
                pushLowFlag: false,/*推下级弹窗 */
				pushLowObj: null,/*推下级对象 */
                pushLowStatus: null,/*记录是否批量推下级*/
                selSchoolList: [],/*选择的下级列表 */
                listData:[],
		    	testLoading:{
		    		status:false,
		    		txt:'加载数据...'
		    	},
		    	listParam:{
					type: 5,
                    platform_id: null,
                    keyword: null,
		    		study_section_id: null,
		    		grade_id: null,
		    		subject_id: null,
		    		type_id: null,
		    		source_id:null,
		       		difficulty_id: null,
		       		status: 1,
		       		page_index: 1,
		       		page_size: 10,
		        },
		       	orgLevel2Param:{ //获取学段参数
					level:2,
					pid:null,
					direction:'balance',
				},
				orgLevel3Param:{ //获取年纪参数
					level:3,
					pid:null,
					direction:'balance',
				},
				orgLevel2:[{id:null,name:'全部'}],
				orgLevel3:[{id:null,name:'全部'}],
				orgSubject:[{id:null,name:'全部'}],
				subjectParam:{ //获取科目,版本，参数
					type:2,
					org_id:null,
					status:1,
				},
				relationParam:{
		    		study_section_id:'',
		    		subject_id:'',
		        },
				total_number:0,
				difficultyData:[],
				// sourceData:[],
				typeIds:[],
				questionTypeData: [],
				statusArr: [
					{
						value: 1,
						name: '未审核',
					},
					{
						value: 2,
						name: '已通过',
					},
					{
						value: 3,
						name: '已拒绝',
					},
				],
				statusDrr: {
					1:{txt:'未审核',color:'#f6a50c'},
					2:{txt:'已通过',color:'#4bd5b0'},
					3:{txt:'已拒绝',color:'#e42929'}
				},
				user_multistage: JSON.parse(sessionStorage.getItem('user_multistage')), // 判断当前是否为多级版本
            	user_level: sessionStorage.getItem('user_level') == 'undefined' ? undefined : JSON.parse(sessionStorage.getItem('user_level')), /*判断当前登录会员是否教育局 */
				platform_id: null,
				platformList: [],/*学校/教育局列表 */
			}
		},
		created(){
			this.getType();
			// this.getSource();
			this.getDifficulty();
			this.getOrgLevel2();
			this.getOrgLevel3();
			this.getSubject();
			this.getList();
			if(this.user_level === 0) {
				this.get_canseeposition();
            }
            if (this.user_multistage) {
            	this.platform_parent();
            }            
		},
		watch:{
// 			'listParam.study_section_id':{
// 	    		handler(newVal,oldVal){
// 					this.listParam.grade_id = null;
// 					this.listParam.subject_id = null;

// 					this.orgLevel3Param.pid = newVal;
// 					this.getOrgLevel3();

// 					this.subjectParam.org_id = newVal;
// 					this.getSubject();

// 					this.relationParam.study_section_id = newVal;

// 					this.getList();
// 　　　　　　　　}
// 			},
// 			'listParam.grade_id':{
// 	    		handler(newVal,oldVal){
// 					this.listParam.subject_id = null;

// 					this.subjectParam.org_id = newVal;
// 					this.getSubject();

// 					this.getList();
// 　　　　　　　　}
// 			},
// 			'listParam.subject_id':{
// 	    		handler(newVal,oldVal){
// 	    			this.relationParam.subject_id = newVal;
// 	    			if(this.listParam.study_section_id !== null ){
// 	    				this.getRelation();
// 	    			}
// 					this.getList();
// 　　　　　　　　}
// 			},
		},
		methods: {
            getImg(content) {
                let temp = content.split('<img src="/public/ueditor/php/upload/image/');
                let data = null;

                temp.forEach((item, index) => {
                    if (index === 0) {
                        data = item;
                    } else {
                        data = data + '<img src="' + this.host_addr + '/public/ueditor/php/upload/image/' + item;
                    }
                })

                return data;
            },
            reset() {
                this.listParam = {
					type: 5,
                    platform_id: null,
                    keyword: null,
		    		study_section_id:null,
		    		grade_id:null,
		    		subject_id:null,
		    		type_id:null,
		    		source_id:null,
		       		difficulty_id:null,
		       		status: 1,
		       		page_index: 1,
		       		page_size: 10,
		        }
                this.getList();
            },
            toLink(link) {
                this.$router.push(link);
            },
			checkShowType(id){
                return true;
				// if( is_empty(id) ){
				// 	return true;
				// }
				// if( !is_empty( this.relationParam.study_section_id) && !is_empty( this.relationParam.subject_id) ){
				// 	if( in_array(id,this.typeIds) ){
				// 		return true;
				// 	}else{
				// 		return false;
				// 	}
				// }else{
				// 	return true;
				// }
			},
			renderAnswer( answer ){
				return (typeof(answer)=='object' && !is_empty(answer))?answer.join(','):answer
			},
			approveQuestion(obj){
				let yes = ( data => {
					let success = (data=>{
                        this.$message.success(data.msg);
                        
	            		if( this.listData.length > 0 && this.listParam.page_index > 1){
	            			this.listParam.page_index--;
                        }
                        
	            		this.getList();
                    })
                    let params = {
                        id: obj.id
                    };
                    
	            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
                    this.$ajax.post("api/level/approve_pushed_receive", params, {func: { success: success }});
                })
                
				let cancel = ( data => {})
                this.e_confirm({yes:yes,cancel:cancel,txt:'确定批准该试题吗？'});
            },
            platform_parent() { /* 获取可推送上级 */
				const success = res => {
					if (!is_empty(res.data)) {
						this.platform = res.data.name;
						this.pid = res.data.id;
					}
				}
				this.$ajax.get('api/level/platform_parent', { params: {},func: {success: success}})
			},
            /* 删除已拒绝的试题 start */
            delQuestion(obj) {
                let ids = null;
                if (this.checkedNames.length === 0) {
                    ids = obj.id;
                } else {
                    ids = this.checkedNames.join(',');
                }

                let yes = ( data => {
					this.delAll(ids);
                })
                
				let cancel = ( data => {})
                this.e_confirm({yes: yes, cancel: cancel, txt:' 确定将试题删除吗？'});              
            },
            delAll(ids) {
                let success = (data => {
                    this.$message.success(data.msg);
                    let len = null;

                    if (ids.length) {
                        len = ids.length;
                    } else {
                        len = 1;
                    }

                    if (this.listData.length - len === 0) {
                        if (this.listParam.page_index > 1) {
                            this.listParam.page_index-- ;
                        } else {
                            this.listParam.page_index = 1;
                        }
                    }

                    this.getList();
                })
                const fail = data => {
                    this.$message.error(data.msg);
                }
                let params = {
                    id: ids,
                    type: 1
                };

                this.$ajax.delete("api/level/delete_pushed_receive", { params: params, func: { success: success, fail: fail }});
            },
             /* 删除已拒绝的试题 end */
             /* 批量试题推上级 start */
            pushUpQuestion(obj) {
                let ids = null;
                if (this.checkedPushNames.length === 0) {
                    ids = obj.id;
                } else {
                    ids = this.checkedPushNames;
                }

                let title = `是否要将资源推送至${this.platform}？（需经过审核）`;
				this.$confirm(title, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
						this.pushUpAll(ids);
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消推送'
					});          
				});
            },
            pushUpAll(ids) {
                let params = {
					id: ids,
					res_type: 'test_question',
					school_id: this.pid,
					push_type: 1,
				}
				const success=res=>{
					this.$message.success(res.msg)
					this.checkedPushNames = [];
					this.getList();
				}
				this.$ajax.post("api/level/push_data", params, {
					func: { success: success }
				});
            },
            /* 批量试题推上级 end */
            /* 批量试题推下级 start */
            pusDownQuestion(obj) {
                this.pushLowObj = obj;
				this.pushLowStatus = null;
                this.pushLowFlag = true;
                
                if (this.checkedPushNames.length === 0) {
                    this.pushUpList.push(obj.id);
                } else {
                    this.pushUpList = this.checkedPushNames;
                }
            },
            getPushLowList(list) {/*获取组件传递列表 */
				this.selSchoolList = list;
            },
            pushLowHide() {/*推下级窗口隐藏 */
				this.pushLowObj = null;
				this.pushLowFlag = false;
			},
            pushActive(flag) {/*推下级执行 */
				if(flag) {
					if(this.selSchoolList.length <= 0) {
						this.$message.error('请选择要推送的下级');
						return;
					}
					let params = {
						id: this.pushUpList,
						res_type: 'test_question',
						school_id: '',
						push_type: 2,
					}
					let arr = [];
					this.selSchoolList.forEach(item=> {
						arr.push(item.id);
					})
					params.school_id = arr.join();
					const success=res=>{
                        this.$message.success(res.msg)
						this.pushLowHide();
                        this.checkedPushNames = [];
                        this.pushUpList = [];
						this.getList();
                    }

					this.$ajax.post("api/level/push_data", params, {
						func: { success: success }
					});
				} else {
					this.pushLowHide();
				}
			},
            /* 批量试题推下级 end */
			rejectQuestion(obj){
				let yes = ( data => {
					let success = (data=>{
                        this.$message.success(data.msg);
                        
	            		if( this.listData.length > 0 && this.listParam.page_index > 1){
	            			this.listParam.page_index--;
                        }
                        
	            		this.getList();
                    })
                    let params = {
                        id: obj.id,
                    };

	            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
                    this.$ajax.put("api/level/refuse_pushed_receive", params, { func: { success: success } });
                })
                
				let cancel = ( data => {})
                this.e_confirm({yes:yes,cancel:cancel,txt:'确定拒绝该试题吗？'});
			},
			getStatusTxt(status){
				return this.statusDrr[parseInt(status)].txt;
			},
			getStatusColor(status){
				return 'color:'+ this.statusDrr[parseInt(status)].color;
			},
			getRelation(){
            	let success = (data=>{
            		this.typeIds  = [];
            		if( data.data.length > 0){
            			for (var i = data.data.length - 1; i >= 0; i--) {
            				this.typeIds.push(parseInt(data.data[i].question_type_id));
            			}
            			
            		}
            	})
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	this.$ajax.get('api/test/question_type_relation',{params: this.relationParam,func:{success:success}})
            },	
			getType(){
            	let success = (data=>{
            		this.questionTypeData = data.data;
            		this.questionTypeData.unshift({id:null,name:'全部'})
            	})
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	this.$ajax.get('api/test/get_question_type',{params: {},func:{success:success}})
            },
			getSource(){
				let success = (data=>{
            		this.sourceData = data.data;
            		this.sourceData.unshift({id:null,name:'全部'})
            	})
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	this.$ajax.get('api/test/test_source',{params: {},func:{success:success}})
			},
			getDifficulty(){
				let success = (data=>{
            		this.difficultyData = data.data;
            		this.difficultyData.unshift({id:null,name:'全部'})
            	})
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	this.$ajax.get('api/test/difficulty',{params: {},func:{success:success}})
			},
			getList(){
                this.testLoading.status = true;
                
            	let success = (data=>{
                    // question_data
            		this.testLoading.status = false;
                    this.listData = data.data.data;
                    this.total_number = data.data.data_sum;
                    
                    if (!is_empty(this.listData)) {
                        this.listData.forEach(item => {
                            if (is_empty(item.question_data)) {
                                item.question_data = {};         
                                item.question_data.question_info = {};
                            }

                            if (is_empty(item.question_data.question_info)) {
                                item.question_data.question_info = {};
                            }
                        })
                    }
            	})
            	let fail =  (data=>{
            		this.testLoading.status = false;
            		this.$message.error(data.msg);
                })
                
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	this.$ajax.get('api/level/push_receive_list', {params: this.listParam, func: {success: success}})
            },
			//获取学段
			getOrgLevel2(){
				let success = ( data=>{
            		this.orgLevel2 = data.data;
            		this.orgLevel2.unshift({id:null,name:'全部学段'})
            	})
            	this.$ajax.get('api/org/org',{params: this.orgLevel2Param,func:{success:success}})
			},
			//获取年级
			getOrgLevel3(){
				let success = ( data=>{
            		this.orgLevel3 = data.data;
            		this.orgLevel3.unshift({id:null,name:'全部年级'})
            	})
            	this.$ajax.get('api/org/org',{params: this.orgLevel3Param,func:{success:success}})
			},
			//获取科目
			getSubject(){
				let success = ( data=>{
            		this.orgSubject = data.data;
            		this.orgSubject.unshift({id:null,name:'全部科目'});
            	})
            	this.$ajax.get('api/cate/subject',{params: this.subjectParam,func:{success:success}})
			},
			
			selected(value){
			  this.listParam.type_id = value;
			  this.getList();
			},
			selected2(value){
			  this.listParam.difficulty_id = value;
			  this.getList();
			},
			selected3(value){
			  this.listParam.source_id = value;
			  this.getList();
			},
			selected4(value){
			  this.listParam.status = value;
			  this.getList();
			},
			handleSizeChange(val) {
				this.listParam.page_index = 1;
		    	this.listParam.page_size = val;
		    	this.getList()
		    },
		    handleCurrentChange(val) {
		    	this.listParam.page_index = val;
		    	this.getList();
			},
			get_canseeposition() {/*获取学校/教育局列表 */
				const success=res=>{
					this.platformList = res.data.data;
				}
				this.$ajax.get('api/level/get_canseeposition_school', { params: {},func: {success: success}})
			},
		},
	}
</script>
<style lang="scss">
	.zh-database-push-check {
		.zh-select-type,.zh-select-type-content {
			width: 100%;
			margin-top: 30px;
			border: 1px solid #e6e6e6;
		}
		.zh-select-type {
			.clear {
				padding: 5px 0;
				border-bottom: 1px solid #e6e6e6;
				.stl {
					width: 6%;
					padding: 5px 0;
					text-align: center;
				}
				.str {
					width: 94%;
					padding-bottom: 5px;
					span {
						display: inline-block;
						margin-right: 2%;
						padding-top: 5px;
						cursor: pointer;
						&:hover {
							color: #409EFF;
						}
					}
				}
			}
			.clear:last-child {
				border-bottom: none;
			}
		}
		.zh-select-type-content {
			.list-option-title {
				padding: 20px 0;
				.option-title-left {
					margin-left: 10px;
					color: #666;
					span {
						display: inline-block;
						margin-left: 30px;
						cursor: pointer;
						&:hover {
							color: #409EFF;
						}
					}
				}
				.option-title-right {
					margin-right: 15px;
				}
			}
			.list-option-content {
				margin-bottom: 20px;
				
                .list-option-list {
                    li {
                        padding-left: 30px;
                        padding-right: 30px;
                    }

                    img {
                        max-width: 100%;
                        max-height: 100%;
                        object-fit: cover;
                    }
                }
			}
			.list-option-explanation {
				background-color: #f9f9f9;
				.option-explanation-left {
					padding: 8px 40px;
					span {
						display: inline-block;
						margin-right: 20px;
					}
					.left-color-hui {
						color: #999;
					}
					.left-color {
						color: #f6a50c;
					}
				}
				.option-explanation-right {
					padding-right: 15px;
				}
				button {
					font-size: 14px;
				}
			}
			.examinationPaper-button {
				padding: 15px 0;
				text-align: center;
			}
		}
		.active,.active2,.active3,.active4 {
		  	color: #409EFF;
		}
	}

    .list-option-answer {      
        .answer-first {
            img {
                max-width: 97%;
                max-height: 100%;
                object-fit: cover;
            }
        }

        ul li:last-child {
            max-height: 82vh;
            overflow-y: auto;

            >span:last-child {
                width: 99%;
            }
        }
    }
</style>
